import cv2
from multiprocessing import Process, Event
from typing import List
import platform
import win32com.client
import subprocess
from camera.camera_driver import CameraDriver


class StartCommand:
    def __init__(self, shared_state):
        """初始化 StartCommand"""
        self._shared_state = shared_state
        self._left_stop_event = Event()
        self._right_stop_event = Event()

    def isCamera(self, index) -> bool:
        """检查设备索引是否是相机"""
        cap = cv2.VideoCapture(index)
        if cap is None or not cap.isOpened():
            return False
        ret, _ = cap.read()
        cap.release()
        return ret

    def getCameraInfo(self, index):
        """获取相机的名称或ID"""
        if platform.system() == "Windows":
            # Windows 系统使用 pywin32 获取相机信息
            try:
                wmi = win32com.client.GetObject("winmgmts:")
                cameras = wmi.ExecQuery(
                    "SELECT * FROM Win32_PnPEntity WHERE Description LIKE '%USB%'"
                )
                camera_list = [
                    device.Description for device in cameras if "VID" in device.DeviceID
                ]
                if index < len(camera_list):
                    return camera_list[index]
                else:
                    return f"相机 {index}"
            except Exception as e:
                print(f"无法获取相机信息: {e}")
                return f"相机 {index}"
        elif platform.system() == "Linux":
            # Linux 系统读取 /dev/video* 设备信息
            try:
                result = subprocess.check_output(
                    f"v4l2-ctl -d /dev/video{index} --all", shell=True
                )
                info = result.decode().split("\n")
                for line in info:
                    if "Driver Info" in line:
                        return line.split(":")[1].strip()
                return f"相机 {index}"
            except Exception as e:
                print(f"无法获取相机信息: {e}")
                return f"相机 {index}"
        else:
            return f"相机 {index}"

    def detectCameras(self) -> List[tuple[int, str]]:
        """动态检测系统中的相机数量并获取相机信息

        Returns:
            list: 可用相机的索引及其名称列表
        """
        available_cameras = []
        index: int = 0
        while True:
            if self.isCamera(index):
                camera_info = self.getCameraInfo(index)
                available_cameras.append((index, camera_info))
            else:
                break
            index += 1

        return available_cameras

    def execute(self, args=None) -> None:
        """启动两个相机并捕获图像"""

        if self._shared_state["cameras_started"]:
            print("相机已启动，不需要再次启动")
            return

        print("正在检测相机...")
        available_cameras = self.detectCameras()

        if len(available_cameras) < 2:
            print("未检测到两个相机，请确保连接了两个相机")
            return
        else:
            print(f"检测到{len(available_cameras)}个相机，请启动相机捕获")

        left_camera_id, left_camera_info = available_cameras[0]
        right_camera_id, right_camera_info = available_cameras[1]

        # 打印检测到的相机信息
        print(f"启动相机: {left_camera_info} (ID: {left_camera_id})")
        print(f"启动相机: {right_camera_info} (ID: {right_camera_id})")

        left_camera_driver = CameraDriver(
            left_camera_id, self._shared_state["left_camera_queue"]
        )
        right_camera_driver = CameraDriver(
            right_camera_id, self._shared_state["right_camera_queue"]
        )

        self._shared_state["left_camera_driver"] = left_camera_driver
        self._shared_state["right_camera_driver"] = right_camera_driver

        # 启动相机捕获
        left_camera_driver.startCapturing()
        right_camera_driver.startCapturing()
        self._shared_state["cameras_started"] = True

        print("所有相机已启动，正在捕获图像...")
